package com.highper.rpc.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author ZhangGJ
 * @Date 2022/02/18 17:34
 */
public class Server {

	public static void main(String[] args) throws IOException {
		ExecutorService executorService = Executors.newCachedThreadPool();
		ServerSocket serverSocket = new ServerSocket(9999);
		System.out.println("服务器已启动");
		while (true) {
			Socket socket = serverSocket.accept();
			System.out.println("有客户端连接");
			executorService.execute(() -> handle(socket));
		}
	}

	private static void handle(Socket socket) {
		System.out.println(
				"线程ID:" + Thread.currentThread().getId() + ", 线程名称:" + Thread.currentThread()
						.getName());
		try {
			InputStream inputStream = socket.getInputStream();
			byte[] b = new byte[1024];
			int read = inputStream.read(b);
			System.out.println("客户端:" + new String(b, 0, read));
			OutputStream outputStream = socket.getOutputStream();
			outputStream.write("OK".getBytes(StandardCharsets.UTF_8));
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
}
